import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ConfirmationService } from 'primeng/primeng';
import { InterceptorService } from '../../../../share/interceptor.service';
import { EducationEntity } from '../../../../models/education-entity';
import { FileUploader } from 'ng2-file-upload'; // 上传文件支持库

// import { setTimeout } from 'timers';
@Component({
  selector: 'app-add-education',
  templateUrl: './add-education.component.html',
  styleUrls: ['./add-education.component.css']
})
export class AddEducationComponent implements OnInit {

  private msgs: any; //提示信息
  private typeData = new Array();
  private educationData = new Array();  //学历实体集合

  public deleteIcon: string = 'assets/images/delete-icon.jpg';//默认图片地址
  //图片和登录信息
  pictureUrls: string[] = [];
  pictureUrl: string;
  pictureUrlAll: string;
  picUrls: string;
  userId: string = localStorage.getItem('userId');
  userCode: string = localStorage.getItem('userCode');
  userPwd: string = localStorage.getItem('userPwd');
  picAllUrls: string[] = [];
  picServerUrl:string='http://tfjybj.com/';//正式
  // picServerUrl:string='http://192.168.22.64/';//开发联调
  // picServerUrl:string='http://192.168.22.65/';//测试
  //查询条件
  private educationId: string = "";  //课程id
  private searchContent = ""; //查询条件
  // 页面表格数据
  private tableUrl: string = "graduate-web/education/findPersonAll" + '/';
  //private tableUrl: string = "http://localhost:8089/graduate-web/education/findPersonAll"+ '/';
  private deleteUrl: string = "graduate-web/education/delete";
  educationInfo: EducationEntity = new EducationEntity();
  editPicture: boolean = true; //修改图片
  btnDelete: boolean = true;
  btnAdd: boolean = true;
  btnEdit: boolean = false;
  btnList: string[] = ["编辑"];
  // '图片'-田晓冰,
  title = ['证书名', '大学名称', '获取时间', '备注'];
  arrbutes = ["certificateName", "universityName", "receiveTime", "remark"];
  isLink = [false, false, false, false, false];
  paging: boolean = true;
  pageSize = 5;
  page = 1;
  total: number;

  sizeList = [5, 10, 20, 50];
  data = new Array();
  btnstyle = [
    { "color": "green" }]

  constructor(private router: Router,
    private confirmationService: ConfirmationService,
    private http: InterceptorService) { }

  ngOnInit() {
    this.getData(true);
  }


  ch = {
    /** 每周第一天，0代表周日 */
    firstDayOfWeek: 0,
    /** 每周天数正常样式 */
    dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
    /** 每周天数短样式（位置较小时显示） */
    dayNamesShort: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
    /** 每周天数最小样式 */
    dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
    /** 每月月份正常样式 */
    monthNames: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    /** 每月月份短样式 */
    monthNamesShort: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
  };

  //查询路径
  //queryEducationUrl = tableUrl;//查询信息
  //queryEducationUrl = "src/assets/mock-data/addEducation.json";//使用假数据
  //查询表格显示的数据-于云丽-2017年12月29日
  getData(isQuery?: boolean) {
    let url = this.tableUrl + this.page + '/' + this.pageSize + '/' + this.userId;
    this.http.get(url).subscribe(
      res => {
        if (res.json().code === "0000") {
          this.data = res.json().data.list;
          this.total = res.json().data.total;
          for (var i = 0; i < res.json().data.list.length; i++) {
            let receiveDate = this.translateDate(new Date(res.json().data.list[i].receiveTime));
            this.data[i].receiveTime = receiveDate;
            console.info(receiveDate);
          }
        }
      }
    )
  }

  changepage(data: any) {
    this.page = data.page;
    this.pageSize = data.pageSize;
    this.getData();
  }


  operatData(obj: any, editModal: HTMLElement) {
    switch (obj.element.innerText) {
      case '编辑':
        this.editOpen(obj.data, editModal);
        break;
      default:
        break;
    }
  }

  // 打开修改模态框
  editOpen(index: any, editModal: HTMLElement) {
    this.pictureUrls = [];
    this.picUrls = '';
    this.picAllUrls = [];
    editModal.style.visibility = 'visible';
    this.educationInfo.id = this.data[index].id;
    this.educationInfo.userId = this.data[index].userId;
    this.educationInfo.isIndmt = this.data[index].isIndmt;
    this.educationInfo.certificateNo = this.data[index].certificateNo;
    this.educationInfo.certificateName = this.data[index].certificateName;
    this.educationInfo.certificateType = this.data[index].certificateType;
    this.educationInfo.receiveTime = this.data[index].receiveTime;
    this.educationInfo.timestampTime = this.data[index].timestampTime;
    this.educationInfo.universityName = this.data[index].universityName;
    this.educationInfo.remark = this.data[index].remark;
    this.educationInfo.operator = this.data[index].operator;
    this.educationInfo.createTime = this.data[index].createTime;
    document.getElementById('certificateName').focus();
    this.picUrls = 'graduate-web/picture/selectPictureById/' + this.educationInfo.id;
    this.http.get(this.picUrls).toPromise().then(
      res => {
        if (res.json().code == '0000') {
          // console.log(res.json().data);
          this.picAllUrls = res.json().data;
        }
        else if (res.json().code == '1111') {
          this.picAllUrls = [];
        }
      }
    );
  }
  // 修改信息
  update(editModel: HTMLElement) {

    if (this.isStrEmpty(this.educationInfo.certificateName)) {
      this.showDialog('证书名称不能为空，请填写确认');
      // this.timing();

      return;
    }

    if (this.isStrEmpty(this.educationInfo.universityName)) {
      this.showDialog('大学名称不能为空，请填写确认');
      //this.timing();

      return;
    }

    if (this.isStrEmpty(this.educationInfo.receiveTime)) {
      this.showDialog('获取时间不能为空，请填写确认');
      //this.timing();

      return;
    }
    //将图片url放入educationinfo
    this.educationInfo.pictureUrls = this.picAllUrls;
    this.educationInfo.receiveTime = this.translateTime(new Date(this.educationInfo.receiveTime));
    this.educationInfo.operator = localStorage.getItem('userName') == undefined ? "大米时代" : this.educationInfo.operator = localStorage.getItem('userName');//操作人名称
    this.educationInfo.operatorId = localStorage.getItem('userId') == undefined ? "bjdmsd" : this.educationInfo.operatorId = localStorage.getItem('userId');//操作人Id
    this.educationInfo.userId = localStorage.getItem('userId') == undefined ? "bjdmsd" : this.educationInfo.operatorId = localStorage.getItem('userId');//创建人ID
    let editUrl = 'graduate-web/education/update/';
    let body = JSON.stringify(this.educationInfo);
    this.http.post(editUrl, body).toPromise().then(
      res => {
        if (res.json().code == '0000') {
          this.getData();
          this.close(editModel);
          this.showDialog(res.json().message);

          console.log(res.json().message + '！！！！！');
        }

      }
    );
  }

  // 提示框
  display: boolean = false;
  messages: '';
  /**
   * 提示框
   */
  showDialog(string) {
    this.messages = string;
    this.display = true;
    let com = this;
    var t = setTimeout(function () { com.display = false }, 1500);

  }
  // 关闭模态框
  close(modal: HTMLElement) {
    this.picAllUrls = [];
    this.pictureUrls = [];
    modal.style.visibility = 'hidden';
    this.educationInfo = new EducationEntity();
  }
  /**
   *modal框可拖拽
  */
  // draggable() {
  //   $('.modal-dialog').draggable();
  // }




  //打开添加模态框
  addOpen(el: HTMLElement, addModal: HTMLElement) {
    this.picAllUrls = [];
    this.pictureUrls = [];
    addModal.style.visibility = 'visible';

    // document.getElementById('userId').focus();
  }

  //添加信息
  add(addModal: HTMLElement) {

    if (this.isStrEmpty(this.educationInfo.certificateName)) {
      this.showDialog('证书名称不能为空，请填写确认');
      // this.timing();

      return;
    }

    if (this.isStrEmpty(this.educationInfo.universityName)) {
      this.showDialog('大学名称不能为空，请填写确认');
      // this.timing();

      return;
    }

    if (this.isStrEmpty(this.educationInfo.receiveTime)) {
      this.showDialog('获取时间不能为空，请填写确认');
      // this.timing();

      return;
    }
    this.educationInfo.receiveTime = this.translateTime(new Date(this.educationInfo.receiveTime));
    this.educationInfo.operator = localStorage.getItem('userName') == undefined ? "大米时代" : "大米时代";//操作人名称
    this.educationInfo.operatorId = localStorage.getItem('userId') == undefined ? "bjdmsd" : this.educationInfo.operatorId = localStorage.getItem('userId');//操作人Id
    this.educationInfo.userId = localStorage.getItem('userId') == undefined ? "bjdmsd" : this.educationInfo.operatorId = localStorage.getItem('userId');//创建人ID
    this.educationInfo.pictureUrls = this.pictureUrls;
    let addUrl = 'graduate-web/education/addEducationList/';
    //let addUrl = 'http://localhost:8090/web/education/addEducationList';

    let array = new Array();
    array.push(this.educationInfo);
    let body = JSON.stringify(array);
    console.log("_________save");
    console.log(body);
    this.http.post(addUrl, body).toPromise().then(
      res => {
        this.getData();//回显

        this.close(addModal);
        this.showDialog(res.json().message);
      }
    );
  }

  // picNew:string[]=[];
//编辑的删除
  deletePic(pictureUrl: any) {
    console.log('===============================================');
    console.log(pictureUrl);
    console.log(this.picAllUrls);
    let picNew = [];

    for (let i = 0; i < this.picAllUrls.length; i++) {
      if (!(this.picAllUrls[i]==pictureUrl)) {
        console.log('this.picAllUrls[i]');
        console.log(this.picAllUrls[i]);
        picNew.push(this.picAllUrls[i]);
      }
    }
    this.picAllUrls = picNew;

  }
//添加的删除
  deletePicAll(pictureUrl: any) {
    console.log('===============================================');
    console.log(pictureUrl);
    console.log(this.picAllUrls);
    let picNew = [];
    let picNew1=[];
    for (let i = 0; i < this.picAllUrls.length; i++) {
      if (!(this.picAllUrls[i]==pictureUrl)) {
        console.log('this.picAllUrls[i]');
        console.log(this.picAllUrls[i]);
        picNew.push(this.picAllUrls[i]);
      }
    }
    this.picAllUrls = picNew;

    for (let i = 0; i < this.pictureUrls.length; i++) {
      if (!(pictureUrl.substring(this.picServerUrl.length,pictureUrl.length)==this.pictureUrls[i])) {
        console.log('this.pictureUrls[i]');
        console.log(this.pictureUrls[i]);
        picNew1.push(this.pictureUrls[i]);
      }
    }
    this.pictureUrls=picNew1;
  }
  //表格添加-于云丽-2017年12月29日
  addInscription(obj: any) {
    localStorage.setItem("isEdit", JSON.stringify(false));
    this.router.navigateByUrl('/workspace/person-info/add-person-info/add-salary');
  }

  deleteDatas(el: any) {
    console.log(this.data[el[0]].id)

    this.confirmationService.confirm({
      message: '你确定删除学历信息吗？',
      accept: () => {
        for (let i = 0; i < el.length; i++) {
          let operator = 'yyl';
          let id = this.data[el[i]].id;
          console.log(this.data[el[i]]);
          let deleteUrl = 'graduate-web/education/deleteById' + '/' + id + '/' + operator;
          let body = JSON.stringify(null);
          this.http.post(deleteUrl, body).subscribe(
            res => {
              if (res.json().code != null && res.json().code == '0000') {
                this.getData();
                this.showDialog(res.json().message);
                this.total--;
              } else {
                this.getData();
              }
            }
          );
        }
      }
    });
  }
  /**
   * 将有格式的替换成没有格式的
   */
  onConvert(obj: any) {
    let showText;
    showText = obj.replace(/&nbsp;/g, ' ');
    showText = showText.replace(/<br>/g, '\n');
    return showText;
  }
  next() {
    this.router.navigateByUrl('/workspace/person-info/add-person-info/add-company'); //可以用相对路径吗
  }

  ////////////////////////////////上传图片有问题，重新书写//////////////////////////////////
  public uploader: FileUploader = new FileUploader({
    // url:"http://localhost:8080/singlePoject/importTest",//要写全路径
    url: this.http.getServerUrl("graduate-web/company/importPicture"),
    method: "POST",
    // allowedFileType:["xls","xlxs"]
  });
  //上传触发事件
  upload() {
    if (this.filename == "") {
      this.showDialog("没有选择文件，请选择文件");
      return;
    }
    let extName = this.filename.substring(this.filename.lastIndexOf('.') + 1);
    if (extName == "jpg" || extName == "JPG" || extName == "jpeg" || extName == "JPEG" || extName == "bmp" || extName == "BMP" || extName == "gif" || extName == "GIF" || extName == "png" || extName == "PNG" || extName == "ico" || extName == "ICO") {
      this.uploadFile();
      this.displayFile = false;
    } else {
      this.showDialog("文件类型不正确，请选择正确的图片文件（.jpg|.jpeg|.bmp|.gif|.png|.ico)");
    }
  }

  //文件上传执行事件
  uploadFile() {
    let obj = this;
    this.uploader.queue[this.uploader.queue.length - 1].upload();

    this.uploader.queue[this.uploader.queue.length - 1].onSuccess = function (response, status, headers) {
      if (status == 200) {
        let tempRes = JSON.parse(response);
        if (tempRes.code == "0000") {
          obj.pictureUrl = tempRes.data;
          obj.pictureUrl=obj.pictureUrl;
          var url=obj.picServerUrl+obj.pictureUrl;//拼接url
          obj.pictureUrls.push(obj.pictureUrl);//图片服务器返回生成的url
          obj.picAllUrls.push(url);//url全路径 ip+图片服务器返回生成的url
          obj.showDialog(tempRes.message);
          console.log(obj.pictureUrls);
          console.log(obj.picAllUrls);
        } else if (tempRes.code == "1111") {
          obj.showDialog(tempRes.message);
          document.getElementById('btnErrorDataShow').setAttribute('style', 'display:visible');
        } else {
          obj.showDialog("文件数据存在无效值，请检查数据格式");
        }
        ///obj.getData();
      }
      else {
        obj.showDialog("与服务连接异常，请重试！");
      }
    };
  }
  filename = "";//页面显示的文件名
  displayFile: boolean = false;
  //打开导入框
  import(info: any) {
    this.filename = "";
    this.displayFile = true;
    // 打开导入框时清除之前选择的文件记录
    let e: any = document.getElementById('filePath');
    e.value = "";
    this.uploader.clearQueue();
  }

  /**
  * 显示选择文件的框
  */
  show(el: HTMLElement) {
    el.click();
  }

  //选择文件后触发的事件
  selectedFileOnChanged(event: any) {
    this.filename = event.target.value;
  }


  //将毫秒数转换成日期
  translateDate(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? '0' + m : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var a = date.getM
    return y + '-' + m + '-' + d;
  }

  /**
     * 时间转化
     * @param date 日期
     */
  translateTime(date) {
    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
  }
  /**
   * 判断字符串是否为 null或为 "" 值，是则返回true，否返回false
   * @param obj 字符串
   */
  //  || obj.trim() == ""
  isStrEmpty(obj: string) {
    if (obj == undefined || obj == null) {
      return true;
    }
    return false;
  }

  private timer;
  private identificateTime: number = 5;

  // 定时关闭弹出框
  timing() {
    this.timer = setInterval(() => {
      this.identificateTime = this.identificateTime - 1;
      if (this.identificateTime <= 0) {
        // clearInterval(this.timer);
        this.closeDialog();
      }
    }, 1000);
    this.identificateTime = 5;
  }


  closeDialog() {
    this.display = false;
  }


  /*****************************上传图片*******************************************/
  //上传配置
  // public uploader: FileUploader = new FileUploader({
  //   url: "http://localhost:8086/graduate-web/picture/FileUpload",
  //   method: "POST",
  //   removeAfterUpload: true
  //   // itemAlias: "file",
  //   // allowedFileType:[".jpeg",".jpg",".png",".bmp",".gif"]
  // });

  // public selectedFileOnChanged() {
  //   this.editPicture = !this.editPicture; //
  //   //上传文件
  //   this.uploader.queue[0].onSuccess = function (response, status, headers) {
  //     //上传文件成功
  //     if (status == 200) {
  //       //上传文件后获取服务器返回的数据
  //       let tempRes = JSON.parse(response);
  //       //修改页面图片
  //       let pictureURL: string = tempRes.data;
  //       let el: Element = document.getElementById('wizardPicturePreview');
  //       el.setAttribute('src', pictureURL);
  //       let el2: Element = document.getElementById('wizard-picture');
  //       el2.setAttribute('class', 'hidePicture');
  //       //存储图片路径
  //       localStorage.setItem('personPictureURL',pictureURL);
  //     } else {
  //       // 上传文件后获取服务器返回的数据错误
  //       this.msgs = [{
  //         severity: 'error',
  //         summary: '提示',
  //         detail: '上传图片失败！'
  //       }]
  //     }

  //   };
  //   // 开始上传
  //   this.uploader.queue[0].upload()
  // };





  /*****************************上传图片第二种实现*******************************************/

  // public uploader: FileUploader = new FileUploader({
  //   // url:"http://localhost:8080/singlePoject/importTest",//要写全路径
  //   // url: this.http.getServerUrl("graduate-web/company/importPicture"),
  //   url: this.http.getServerUrl("graduate-web/education/importPicture"),
  //   method: "POST",
  //   // allowedFileType:["xls","xlxs"]
  // });

  // filename = "";//页面显示的文件名
  // displayFile: boolean = false;
  // //打开导入框
  // import(info: any) {
  //   console.log("执行到这里了");
  //   this.filename = "";
  //   this.displayFile = true;
  //     // 打开导入框时清除之前选择的文件记录
  //    let e: any = document.getElementById('filePath');
  //     e.value = "";

  //   this.uploader.clearQueue();

  // }

  // /**
  // * 显示选择文件的框
  // */
  // show(el: HTMLElement) {
  //   console.log("2");
  //   el.click();
  // }

  // //选择文件后触发的事件
  // selectedFileOnChanged1(event: any) {
  //   console.log("3");
  //   this.filename = event.target.value;
  // }

  // //上传触发事件
  // upload() {
  //   if (this.filename == "") {
  //     console.log("上传文件开始");
  //     this.showDialog("没有选择文件，请选择文件");
  //     return;
  //   }
  //   console.log("3");
  //   let extName = this.filename.substring(this.filename.lastIndexOf('.') + 1);
  //   console.log("4");
  //   if (extName == "jpg" || extName == "bmp" || extName == "gif" || extName == "png") {
  //     console.log("5");
  //     this.uploadFile();
  //     console.log("6");
  //     this.displayFile = false;
  //   } else {
  //     this.showDialog("文件类型不正确，请选择正确的Excel文件（.xls|.xlsx）");
  //   }
  // }

  // //文件上传执行事件
  // uploadFile() {
  //   console.log("7");
  //   let obj = this;
  //   this.uploader.queue[this.uploader.queue.length - 1].upload();
  //   console.log("8");
  //   this.uploader.queue[this.uploader.queue.length - 1].onSuccess = function (response, status, headers) {
  //     if (status == 200) {
  //       let tempRes = JSON.parse(response);
  //       console.log("9");
  //       if (tempRes.code == "0000") {
  //         console.log("10");
  //         obj.showDialog(tempRes.message);
  //       } else if (tempRes.code == "1111") {
  //         console.log("11");
  //         obj.showDialog(tempRes.message);
  //         document.getElementById('btnErrorDataShow').setAttribute('style', 'display:visible');
  //       } else {
  //         console.log("12");
  //         obj.showDialog("文件数据存在无效值，请检查数据格式");
  //       }
  //       ///obj.getData();
  //     }
  //     else {
  //       obj.showDialog("与服务连接异常，请重试！");
  //     }
  //   };
  // }



}
